//
//  SMSCodeInputVC.m
//  EPTool
//
//  Created by guoshiqing on 2018/4/16.
//  Copyright © 2018年 云数动能科技. All rights reserved.
//

#import "SMSCodeInputVC.h"
#import "PasswordInputVC.h"

#import "MQVerCodeInputView.h"
#import "Macro.h"
#import "UIView+DDAddition.h"
#import "GlobalUtil.h"
#import "TimerView.h"
#import "NotificationHelp.h"
#import "AccountSysVM.h"
#import "ErrorCode.h"
#import "UserSettings.h"

@interface SMSCodeInputVC ()

// 静态控件
@property (nonatomic, strong) UILabel *lblTitle;
@property (nonatomic, strong) UILabel *lblMessage;

// 动态控件
@property (nonatomic, strong) UILabel *lblMobile;
@property (nonatomic, strong) MQVerCodeInputView *smsCodeView;
@property (nonatomic, strong) TimerView *timerView;

@property (nonatomic, copy) NSString *strAreaCode;
@property (nonatomic, copy) NSString *strMobile;
@property (nonatomic, copy) NSString *strSmsCode;
@property (nonatomic, copy) NSString *tempToken;

@property (nonatomic, assign) BOOL isNextOpt;
@end

@implementation SMSCodeInputVC

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addSubviews];
}

#pragma mark - 接口调用返回结果处理
- (void)handelRequestData:(BaseJSONEntity *)returnValue
{
    [self hideProcessingHud];
    if (0 != returnValue.ret) {
        // 验证码确认, 手机号已经绑定了相应的第三方账号
        if ([returnValue.url isEqualToString:RegisterCheckSmsUrl] && (returnValue.ret == C_Login_PhoneIsAlready)) {
            NSString *password = @"123456"; // 这里不会覆盖原密码，只是绑定
            if (ForBindingMobileTypeFromWX == self.type) {
                [(AccountSysVM *)self.baseVM checkPwdForRegisterFromWXWithAreaCode:self.strAreaCode andMobile:self.strMobile andSmsCode:self.strSmsCode andPwd:password andOpenId:UserSaveInfo.WXOpenID andAccessToken:UserSaveInfo.WXAccessToken];
            } else if (ForBindingMobileTypeFromFB == self.type) {
                [(AccountSysVM *)self.baseVM checkPwdForRegisterFromFBWithAreaCode:self.strAreaCode andMobile:self.strMobile andSmsCode:self.strSmsCode andPwd:password andOpenId:UserSaveInfo.FBOpenID andAccessToken:UserSaveInfo.FBAccessToken];
            }
            return;
        }
        
        if (self.isNextOpt) self.isNextOpt = NO;
        [self showAlertWithTitle:returnValue.msg];
        return;
    }
    
    if ([returnValue.url isEqualToString:RegisterCheckPwdFromFBUrl] || [returnValue.url isEqualToString:RegisterCheckPwdFromWXUrl]) {
        UserSaveInfo.WXOpenID = @"";
        UserSaveInfo.WXAccessToken = @"";
        UserSaveInfo.FBOpenID = @"";
        UserSaveInfo.FBAccessToken = @"";
        // 保存用户信息
        [NotificationHelp postNotification:NotificationLoginSuccess object:returnValue.data];
        NSString *token = [returnValue.data objectForKey:@"d-tk"];
        if (token && 0 != token.length) UserSaveInfo.token = token;
        UserSaveInfo.areaCode = self.strAreaCode;
        UserSaveInfo.mobile = self.strMobile;
        [NotificationHelp postNotification:NotificationGo2MainTBC object:nil];
        return;
    }
    
    // 区分下一步和重发验证码
    if (self.isNextOpt) {
        self.isNextOpt = NO;
        
        if ([returnValue.data isKindOfClass:[NSDictionary class]]) {
            NSString *token = [returnValue.data objectForKey:@"d-tk"];
            if (token && 0 != token.length) self.tempToken = token;
        }
        [self nextAction];
    }
    else
    {
        // 网络请求，并重新开始定时60秒
        [self.timerView startTimer];
    }
}

- (void)addSubviews
{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.lblTitle];
    self.lblTitle.top = 16.0f;
    [self.view addSubview:self.lblMessage];
    self.lblMessage.top = self.lblTitle.bottom + 8.f;
    [self.view addSubview:self.lblMobile];
    self.lblMobile.centerY = self.lblMessage.centerY;
    self.lblMobile.left = self.lblMessage.right;
    [self.view addSubview:self.smsCodeView];
    self.smsCodeView.top = self.lblMessage.bottom + 53.f;
    [self.view addSubview:self.timerView];
    self.timerView.top = self.smsCodeView.bottom + 16.f;
    
    WEAKSELF
    self.timerView.blockOfClick = ^{
        [weakSelf btnResendVerCodeClick];
    };
    
    self.smsCodeView.block = ^(NSString *text){
        if (4 == text.length) {
            [weakSelf checkSmsCode:text];
        }
    };
}

#pragma mark - 调用接口检查验证码是否正确
- (void)checkSmsCode:(NSString *)smsCode
{
    self.isNextOpt = YES;
    
    self.strSmsCode = smsCode;
    [self showProcessingHud:@"..."];
    if (ForRegisterType == self.type) {
        [(AccountSysVM *)self.baseVM checkSmsCodeForRegisterWithAreaCode:self.strAreaCode andMobile:self.strMobile andSmsCode:self.strSmsCode andSource:@"phone"];
    }
    else if (ForForgotType == self.type) {
        [(AccountSysVM *)self.baseVM checkSmsCodeForRetrievePwdWithAreaCode:self.strAreaCode andMobile:self.strMobile andSmsCode:self.strSmsCode];
    }
    else if (ForModifyMobileType == self.type) {
        [(AccountSysVM *)self.baseVM checkSmsCodeForModifyMobileWithAreaCode:self.strAreaCode andMobile:self.strMobile andSmsCode:self.strSmsCode andPwd:self.pwd];
    }
    else if (ForBindingMobileTypeFromWX == self.type) {
        [(AccountSysVM *)self.baseVM checkSmsCodeForRegisterWithAreaCode:self.strAreaCode andMobile:self.strMobile andSmsCode:self.strSmsCode andSource:@"weixin"];
    }
    else if (ForBindingMobileTypeFromFB == self.type) {
        [(AccountSysVM *)self.baseVM checkSmsCodeForRegisterWithAreaCode:self.strAreaCode andMobile:self.strMobile andSmsCode:self.strSmsCode andSource:@"facebook"];
    }
}

#pragma mark - 懒加载
- (UILabel *)lblTitle
{
    if (!_lblTitle) {
        _lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(LoginVC_X, 0, LoginVC_W, 32.f)];
        _lblTitle.text = @"请输入验证码";
    }
    return _lblTitle;
}

- (UILabel *)lblMessage
{
    if (!_lblMessage) {
        _lblMessage = [[UILabel alloc] initWithFrame:CGRectMake(LoginVC_X, 0, 100, 17.f)];
        _lblMessage.font = SystemFont(12.f);
        _lblMessage.text = @"验证码已发送至手机：";
        CGSize size = [GlobalUtil sizeFortext:_lblMessage.text withFont:_lblMessage.font constrainedToSize:CGSizeMake(200.f, 17.f)];
        _lblMessage.width = size.width;
    }
    return _lblMessage;
}

- (UILabel *)lblMobile
{
    if (!_lblMobile) {
        _lblMobile = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 17.f)];
        _lblMobile.font = SystemFont(12.f);
        _lblMobile.textColor = RGB_BLUE;
    }
    return _lblMobile;
}

- (void)setAreaCode:(NSString *)areaCode andMobile:(NSString *)mobile
{
    self.strAreaCode = areaCode;
    self.strMobile = mobile;
    self.lblMobile.text = [NSString stringWithFormat:@"+%@ %@", areaCode, mobile];
}

- (MQVerCodeInputView *)smsCodeView
{
    if (!_smsCodeView) {
        _smsCodeView = [[MQVerCodeInputView alloc] initWithFrame:CGRectMake(LoginVC_X, 0, LoginVC_W, 50.f)];
        _smsCodeView.maxLenght = 4;
        _smsCodeView.keyBoardType = UIKeyboardTypeNumberPad;
        [_smsCodeView mq_verCodeViewWithMaxLenght];
    }
    return _smsCodeView;
}

- (TimerView *)timerView
{
    if (!_timerView) {
        _timerView  = [[TimerView alloc] initWithFrame:CGRectMake(LoginVC_X, 0, 200, Cell_H)];
        [_timerView setLabelTransparency:TIMERVIEWSTATE_FULLDISPLAY];
        [_timerView startTimer];
    }
    return _timerView;
}

#pragma mark - 点击重新发送验证码
- (void)btnResendVerCodeClick
{
    // 重新请求验证码
    [self showProcessingHud:@"..."];
    if (ForRegisterType == self.type) {
        [(AccountSysVM *)self.baseVM registerSmsCodeRequestWithAreaCode:self.strAreaCode andMobile:self.strMobile andSource:@"phone"];
    }
    else if (ForForgotType == self.type) {
        [(AccountSysVM *)self.baseVM retrievePwdSmsCodeRequestWithAreaCode:self.strAreaCode andMobile:self.strMobile];
    }
    else if (ForModifyMobileType == self.type) {
        [(AccountSysVM *)self.baseVM modifyMobileSmsCodeRequestWithAreaCode:self.strAreaCode andMobile:self.strMobile];
    }
    else if (ForBindingMobileTypeFromWX == self.type) {
        [(AccountSysVM *)self.baseVM registerSmsCodeRequestWithAreaCode:self.strAreaCode andMobile:self.strMobile andSource:@"weixin"];
    }
    else if (ForBindingMobileTypeFromFB == self.type) {
        [(AccountSysVM *)self.baseVM registerSmsCodeRequestWithAreaCode:self.strAreaCode andMobile:self.strMobile andSource:@"facebook"];
    }
}

#pragma mark - 实现点击下一步事件
- (void)nextAction
{
    // 修改登录手机号，跳转到首页
    if (self.type == ForModifyMobileType) {
        UserSaveInfo.areaCode = self.strAreaCode;
        UserSaveInfo.mobile = self.strMobile;
        [NotificationHelp postNotification:NotificationGo2MainTBC object:nil];
    }
    else
    {
        PasswordInputVC *pwdVC = [[PasswordInputVC alloc] init];
        pwdVC.baseVM = [[AccountSysVM alloc] init];
        pwdVC.type = self.type;
        pwdVC.tempToken = self.tempToken;
        [pwdVC setAreaCode:self.strAreaCode andMobile:self.strMobile andSmsCode:self.strSmsCode];
        [self.navigationController pushViewController:pwdVC animated:YES];
    }
}

@end
